package ua.org.nuos.sdms.clientgui.client.view;

import com.vaadin.ui.*;
import ua.org.nuos.sdms.clientgui.client.components.factory.ButtonFactory;
import ua.org.nuos.sdms.clientgui.client.components.factory.LayoutFactory;
import ua.org.nuos.sdms.clientgui.client.components.factory.WindowFactory;
import ua.org.nuos.sdms.clientgui.client.components.window.AbstractWindow;
import ua.org.nuos.sdms.clientgui.client.controller.GlobalBoard;
import ua.org.nuos.sdms.clientgui.client.events.LoginEvent;
import ua.org.nuos.sdms.clientgui.client.events.ShowRegisterNewUserLayoutEvent;
import ua.org.nuos.sdms.clientgui.server.AppProxy;

/**
 * Created by IntelliJ IDEA.
 * User: dio
 * Date: 19.02.12
 * Time: 20:08
 * To change this template use File | Settings | File Templates.
 */
public class LoginWindow extends AbstractWindow implements LoginForm.LoginListener, Button.ClickListener {

    private static final String WIDTH = "350";
    private static final String LOGIN_HEIGHT = "220";
    private static final String CAPTION = "Введите свой email и пароль";

    public static final String REGISTRATION_LAYOUT_ID = "Registration Layout";
    public static final String ID = LoginWindow.class.getSimpleName();

    public LoginWindow() {
        init();
    }

    private void init() {
        LoginForm loginForm = new LoginForm();
        loginForm.setWidth("100%");
        loginForm.setUsernameCaption("Логин");
        loginForm.setPasswordCaption("Пароль");
        loginForm.setLoginButtonCaption("Войти");
        loginForm.addListener(this);

        Button registration = ButtonFactory.getButton("Регистрация", this);
        ButtonFactory.setButtonColorStyle(registration, ButtonFactory.Color.BLUE);
        Label label = new Label("У Вас нет аккаунта?");
        HorizontalLayout registrationLayout = LayoutFactory.getHLayout(label, registration);
        registrationLayout.setWidth("100%");
        registrationLayout.setComponentAlignment(registration, Alignment.MIDDLE_RIGHT);
        registrationLayout.setExpandRatio(label, 1.f);
        AppProxy.getInstance().getComponentLocator().addContainer(REGISTRATION_LAYOUT_ID, registrationLayout);

        window = WindowFactory.getModalWindow(WIDTH, LOGIN_HEIGHT, CAPTION);
        window.addComponent(loginForm);
        window.addComponent(registrationLayout);

        AppProxy.getInstance().getComponentLocator().addWindow(ID, this);
    }

    @Override
    public void onLogin(LoginForm.LoginEvent loginEvent) {
        String user = loginEvent.getLoginParameter("username");
        String password = loginEvent.getLoginParameter("password");
        LoginEvent event = new LoginEvent(user, password);
        AppProxy.getInstance().getControllerLocator().getController(GlobalBoard.ID).fire(event);
    }

    @Override
    public void buttonClick(Button.ClickEvent event) {
        AppProxy.getInstance().getController(GlobalBoard.ID).fire(new ShowRegisterNewUserLayoutEvent());
    }
}
